import { useStore } from '@/hooks';
import { Button, Dialog, Form, Message } from '@alifd/next';
import TauTable from '@/components/TauTable';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid, TitleGrid, column, model } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';

const FromItem = Form.Item;

const modelVI = model.vehicleInfos;
const modelDI = model.driverInfos;

const DataForm = ({ onCancel, modal, onSubmit, ...formProps }) => {
  const { memberStore: store } = useStore();
  const {
    show,
    record,
    toClose,
  } = modal;
  const [driver] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(show === 'view');
  const [state, setState] = useState([]);
  const [dIState, setDIState] = useState([]);
  const [stateMOP, setStateMOP] = useState([]);
  const [driverMenu, setDriverMenu] = useState([]);
  const [curCharge, setCurCharge] = useState();

  useEffect(() => { if (toClose?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      if (record) {
        const port = await store.getDicts('port');
        const tempMenu = port.reduce((acc, cur) => {
          acc[cur.value] = cur.label;
          return acc;
        }, {});
        setDriverMenu(tempMenu);
        await initExtras(record);
        editCtx.origin = _.cloneDeep({});
        _.assign(driver, {});
      } else {
        _.set(driver, 'noticeRules', []);
      }
    })();
  }, []);

  async function initExtras(res) {
    try {
      const vehicles = await store.getVehicles({ search: { phone: res?.phone }, pg: { size: 10, page: 0, sort: ['crDate;desc'] } });
      const drivers = await store.getMemberDriver({ phone: res?.phone });
      const tempVehicle = vehicles.map((p) => ({
        ...p,
        driverIds: p.driverInfos.map((j) => j.mainPhone),
      }));
      setState(tempVehicle);
      setDIState(drivers);
    } catch (error) {
      console.log('🚀 _ file: DataForm.jsx:79 _ error:', error);
      throw error;
    }
  }

  const overrideModel = {
    vehicleInfos: {
      ui: {
        renderer: () => {
          return (
            <>
              <TauTable
                hidePagination
                dataSource={state}
                columns={[
                  { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
                  column('mainlandLicense', { width: 100 }, modelVI),
                  column('hkLicense', { width: 100 }, modelVI),
                  column('ports', {
                    width: 150,
                    cell: (v) => {
                      const temp = v?.map((p) => driverMenu[p]);
                      return (<>{temp?.join('，')}</>);
                    },
                  }, modelVI),
                  column('vehicleModel', { width: 100 }, modelVI),
                  column('passengerCapacity', { width: 88 }, modelVI),
                  column('driverInfos', {
                    width: 200,
                    cell: (v) => {
                      return <>{v?.map((p) => p.name)?.join('、')}</>;
                    },
                  }, modelVI),
                  // column('attachments', {
                  //   width: 66,
                  //   cell: (v, i, r) => {
                  //     const count = v?.reduce((acc, item) => {
                  //       acc += item.binaryId?.length;
                  //       return acc;
                  //     }, 0);
                  //     return <Button text type="primary" onClick={() => handleEdit(r, 'VI')}>{v ? `${count} 张` : t`无`}</Button>;
                  //   },
                  // }, modelVI),
                ]}
              />
            </>
          );
        },
        span: 4,
      },
    },
    driverInfos: {
      ui: {
        renderer: () => {
          return (
            <>
              <TauTable
                hidePagination
                dataSource={dIState}
                columns={[
                  { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
                  column('name', { width: 200 }, modelDI),
                  column('mainPhone', { width: 260 }, modelDI),
                  column('hkPhone', { width: 260 }, modelDI),
                  column('wxAccount', { width: 260 }, modelDI),
                ]}
              />
            </>
          );
        },
        span: 4,
      },
    },
  };

  const handleEdit = (r) => {
    setCurCharge(r);
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(driver, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: ActivityForm.jsx:213 _ errors:', errors);
      return;
    }
    _.set(driver, 'priceRules', [...state, ...stateMOP]);
    onSubmit?.(driver);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  // 'groupNames', 'fullname', 'nickname', 'phone', 'type', 'crDate',

  return (
    <Form
      {...formProps}
      value={driver}
      onChange={handleChange}
      inline
      useLabelForErrorMessage
    >
      <FieldsGrid
        formData={driver}
        mode={show}
        columns={4}
        overrideModel={overrideModel}
        fields={[
          'vehicleInfos', 'driverInfos',
        ]}
      />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(DataForm);
